// 服务层 api 插件
import axios from '@/plugins/axios'
import {API_DEFAULT_CONFIG, HTTP_PATH_REGULAR} from '@/config'
import API_CONFIG from '@/service'
import Vue from 'vue'

function normalize(options, data) {
  if (options.method === 'GET') {
    options.params = data
  } else {
    options.data = data
  }
  return options
}

export {normalize}

function jointUrl(url, data) {
  const tmpAttrNames = []
  const tmpItems = url.split('/')
  const check = (item) => {
    if (HTTP_PATH_REGULAR.test(item)) {
      tmpAttrNames.push(item.match(HTTP_PATH_REGULAR)[1])
      return window.R.propOr('', item.match(HTTP_PATH_REGULAR)[1], data)
    }
    return item
  }
  const tmpAttrValues = window.R.map(check, tmpItems)
  const deleteFromData = (name) => Vue.delete(data, name)

  window.R.forEach(deleteFromData, tmpAttrNames)
  return tmpAttrValues.join('/')
}

export {jointUrl}

class MakeApi {
  constructor(options) {
    this.api = {}
    this.apiBuilder(options)
  }

  apiBuilder({sep = '|', config = {}, mock = false, mockBaseURL = '', baseURL = ''}) {
    Object.keys(config).map(namespace => {
      return this.apiSingleBuilder({
        namespace,
        mock,
        mockBaseURL,
        baseURL,
        sep,
        config: config[namespace]
      })
    })
  }

  apiSingleBuilder({namespace, sep = '|', config = {}, mock = false, mockBaseURL = '', baseURL = ''}) {
    config.forEach(api => {
      const {name, desc, params, method, path, mockPath, apiMock} = api
      const url = mock || apiMock ? mockPath : path//控制走 mock 还是线上
      const tmpBaseURL = mock || apiMock ? mockBaseURL : baseURL

      Object.defineProperty(this.api, `${namespace}${sep}${name}`, {
        value(outerParams, outerOptions, onlyUrl = false) {
          const data = !outerParams ? params : outerParams
          const option = normalize(Object.assign({
            url: jointUrl(url, data),
            desc,
            baseURL: tmpBaseURL,
            method
          }, outerOptions), data)

          if (onlyUrl) {
            let requestUrl = `${option['baseURL']}${option['url']}`

            if (!window.R.isNil(option['params']) && !window.R.isEmpty(option['params'])) {
              requestUrl += '?'
              window.R.forEach((key) => {
                requestUrl += `${key}=${option['params'][key]}&`
              }, window.R.keys(option['params']))
            }
            return requestUrl
          }
          return axios(option)
        }
      })
    })
  }
}

// 注入模型和全局配置，并暴露出去
export default new MakeApi({
  config: API_CONFIG,
  ...API_DEFAULT_CONFIG
})['api']
